#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Created on 2011/06/06

'''
from UserCommentDetail import UserCommentDetail
from UserCommentKeyword import UserCommentKeyword
from google.appengine.api import users
from google.appengine.ext import db, webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
import datetime
import dateutil.parser
import os
import re
import string
import sys
import traceback

class MemberData(db.Model):
    memberEmail = db.StringProperty(required=True, multiline=False)
    isLogin = db.BooleanProperty()

class MainPage(webapp.RequestHandler):
    def get(self):
        try:
            user = users.get_current_user()
            members = MemberData.gql('WHERE memberEmail = :1', user.email())
            member = members.get()
            if member is None:
                self.redirect(users.create_login_url(self.request.uri))
            elif member.isLogin:
                self.response.headers['Content-Type'] = 'text/html;UTF-8'
                
                date = self.request.get('date')
                word = self.request.get('word', None)
                kind = self.request.get('kind', 'AndroidMarket.csv')
                if word is None:
                    userCommentkeyword = UserCommentKeyword()
                    navbar = userCommentkeyword.outCommentKeywordFromDB(kind)
                    notSelectedKind = userCommentkeyword.outNotSelectedKindFromDB(kind)
                    data = { "kind" : kind, "not_selected_kind" : notSelectedKind, "comment_table":navbar, "sign_out_url": users.create_logout_url(self.request.path)}
                    path = os.path.join( os.path.dirname( __file__ ), "user_comment_keyword.html" )
    
                else: # 詳細
                    navbar = u''
                #    rowCount = entry.row_count.text
                    userCommentDetail = UserCommentDetail()
                    navbar = userCommentDetail.outCommentDetailFromDB(kind, date, word)
                
                    data = { "comment_table":navbar, "sign_out_url": users.create_logout_url(self.request.path)}
                    path = os.path.join( os.path.dirname( __file__ ), "user_comment_detail.html" )
    
                html = template.render(path, data)
                self.response.headers['Content-Type'] = 'text/html'
                self.response.out.write(html)
            else:
                self.redirect(users.create_login_url(self.request.uri))
        except Exception:
            message = []
            message.append('<pre>')
            value = " Error \n %s:%s" % (sys.exc_info()[0], sys.exc_info()[1])
            value = re.sub("<", "&lt;", value)
            value = re.sub(">", "&gt;", value)
            message.append(value)
            message.append('\nPlease send message for Administrator.')
            message.append('</pre>')
            navbar = "".join(message)
            data = { "message":navbar, "sign_out_url": users.create_logout_url(self.request.path)}
            path = os.path.join( os.path.dirname( __file__ ), "error.html" )
            html = template.render(path, data)
            self.response.headers['Content-Type'] = 'text/html'
            self.response.out.write(html)
        
    def post(self):
        try:
            type = self.request.get('type', None)
            if type == 'keyword':
                csvData = self.request.get('csv', '')
                kind = self.request.get('kind', '')
                userCommentkeyword = UserCommentKeyword()
                userCommentkeyword.updateCommentKeyword(csvData, kind)
            elif type == 'comment':
                csvData = self.request.get('csv', '')
                kind = self.request.get('kind', '')
                date = self.request.get('date', '')
                userCommentDetail = UserCommentDetail()
                userCommentDetail.updateComment(csvData, kind, date)
            self.redirect('/')
        except Exception:
            message = []
            message.append('<pre>')
            value = " Error \n %s:%s" % (sys.exc_info()[0], sys.exc_info()[1])
            value = re.sub("<", "&lt;", value)
            value = re.sub(">", "&gt;", value)
            message.append(value)
            message.append('\nPlease send message for Administrator.')
            message.append('</pre>')
            navbar = "".join(message)
            data = { "message":navbar, "sign_out_url": users.create_logout_url(self.request.path)}
            path = os.path.join( os.path.dirname( __file__ ), "error.html" )
            html = template.render(path, data)
            self.response.headers['Content-Type'] = 'text/html'
            self.response.out.write(html)

class ControlPanelPage(webapp.RequestHandler):
    def get(self):
        user = users.get_current_user()
        if user:
            self.response.headers['Content-Type'] = 'text/html;UTF-8'
            
            path = os.path.join( os.path.dirname( __file__ ), "control_panel.html" )

            html = template.render(path, None)
            self.response.headers['Content-Type'] = 'text/html'
            self.response.out.write(html)
        else:
            self.redirect(users.create_login_url(self.request.uri))
    def post(self):
        user = users.get_current_user()
        type = self.request.get('type', None)
        try:
            if user:
                if type == 'deleteKeyword':
                    userCommentkeyword = UserCommentKeyword()
                    userCommentkeyword.deleteKeyword()
                elif type == 'deleteComment':
                    userCommentDetail = UserCommentDetail()
                    userCommentDetail.deleteComment()
                elif type == 'updateKind':
                    userCommentDetail = UserCommentDetail()
                    userCommentDetail.updateKind()
                elif type == 'registMember':
                    member = MemberData(memberEmail = user.email())
                    member.isLogin = True
                    member.put()
                self.redirect('/')
        except Exception:
            message = []
            message.append('<pre>')
            value = " Error \n %s:%s" % (sys.exc_info()[0], sys.exc_info()[1])
            value = re.sub("<", "&lt;", value)
            value = re.sub(">", "&gt;", value)
            message.append(value)
            message.append('\nPlease send message for Administrator.')
            message.append('</pre>')
            navbar = "".join(message)
            data = { "message":navbar, "sign_out_url": users.create_logout_url(self.request.path)}
            path = os.path.join( os.path.dirname( __file__ ), "error.html" )
            html = template.render(path, data)
            self.response.headers['Content-Type'] = 'text/html'
            self.response.out.write(html)

application = webapp.WSGIApplication([('/', MainPage),('/detail', MainPage), ('/update', MainPage), ('/control', ControlPanelPage)], debug=True)


def main():
    run_wsgi_app(application)

if __name__ == '__main__':
    main()
